"""
func: 写入或读取数据库的模块
"""
from datetime import datetime, timedelta
from typing import Dict, List
from kds_util.user_logbook import user_log as logger
from highlow.dd_obj import TBkId, BkItem, BreedItem, TBreed, OpenOptItem
from highlow.envs import Envs


def insert_strategy_opt_position(strategy_type, opt_type, contract, breed_side, change_position,
                                 expect_position, margin: float, profit: float, opt_status: int,
                                 opt_price: float, kt: str, multiplier: int, opts: Dict[str, OpenOptItem], mysql,
                                 remark=""):
    """ 写入策略操作表：开仓，加仓，减仓，平仓
    """
    key = "{}.{}".format(contract, breed_side)
    dt = datetime.strptime(kt, "%Y-%m-%d %H:%M:%S")
    if opt_type == "open":  # 只获取开仓数据，重开仓的开仓也是开仓
        # opens[key] = abs(change_position)  # 更新开仓数据
        opts[key] = OpenOptItem(contract, breed_side, opt_price, abs(change_position), dt, multiplier)
    elif opt_type == "close":
        if key in opts:
            # opts[key].close_opt(opt_price, change_position, dt, opt_status)
            del opts[key]

    record_time = kt
    status = 1 if opt_status else 0
    sql = "replace into tbl_strategy_opt_position(trade_day,record_time,strategy_type,opt_type,contract,breed_side," \
          "change_position,new_position,margin,profit,opt_status,opt_price,multiplier, remark)" \
          "values('{}','{}','{}','{}','{}',{},{},{},{}," \
          "{},{},{},{},'{}')". \
        format(Envs.cur_trade_day, record_time, strategy_type, opt_type, contract, breed_side, change_position,
               expect_position, margin, profit, status, opt_price, multiplier, remark)
    rel = mysql.exec(sql)
    logger.info(f"写入策略：{rel}, [{record_time}], {strategy_type}, {opt_type}, {contract},side:{breed_side}, "
                f"change:{change_position}, new:{expect_position}, price:{opt_price}, {remark}")
    return
